<template>
  <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="0" size="large">
    <!-- 用户输入框 -->
    <el-form-item prop="username">
      <!-- prefix-icon这个属性是给form表单中的input添加icon图标  clearable一键清空 placeholder输入框为空时输入框默认显示的字-->
      <el-input v-model="ruleForm.username" prefix-icon="user" clearable :placeholder="$t('login.userError')"></el-input>
    </el-form-item>
    <!-- 密码输入框 -->
    <el-form-item prop="password">
      <!-- show-password点击小眼睛可以看见输入的东西 -->
      <el-input v-model="ruleForm.password" prefix-icon="lock" clearable show-password :placeholder="$t('login.PWPlaceholder')"></el-input>
    </el-form-item>
    <!-- 验证码 -->
    <el-form-item>
      <div class="image_rule">
        <!-- 验证码输入框 -->
        <el-input v-model="ruleForm.captcha" prefix-icon="CircleCheck" clearable :placeholder="$t('login.PWError')"></el-input>
        <!-- 图形验证码 -->
        <el-image :src="captchaUrl" class="image" @click="getCaptcha"></el-image>
      </div>
    </el-form-item>
    <!-- 记住我 -->
    <div class="rememberMe">
      <div>
        <el-checkbox
          :label="$t('login.remember')"
          v-model="memoPassword"
          @change="onMemoPassWord"
        ></el-checkbox>
      </div>
      <div>
        <router-link to="">{{ $t('login.forgetPassword') }}</router-link>
      </div>
    </div>
    <!-- 登录按钮 -->
    <el-form-item>
      <el-button type="primary" round style="width: 100%" @click="login(ruleFormRef)">{{
        $t('login.signIn')
      }}</el-button>
    </el-form-item>
  </el-form>
</template>

<script setup lang="ts">
import { reactive, ref, onBeforeMount, Ref } from 'vue'
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
// const { proxy } = getCurrentInstance() as ComponentInternalInstance;
// const aaa = proxy?.$t('login.mobileError')
// 引入api
import { captchaImage, LoginJson } from '@api/login'
// 引入hooks工具类
import userLogin from '@hooks/userLogin';
// 加密
import { Encrypt, Decrypt} from '@utils/aes';
const captchaUrl = ref<string>('');
// 引入定义的类型
import { UserRuleForm } from "@interface/login"
// 定义的类型
const ruleFormRef = ref<FormInstance>()
// 和上面的定义的类型内容一样
const ruleForm = reactive<UserRuleForm>({
  username: '',
  password: '',
  key: '',
  captcha: ''
})

//表单校验规则
const rules = reactive<FormRules<UserRuleForm>>({
  username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
})

// 图形验证码 刚开始进入页面调用一次 也就是生命周期onBeforeMount 点击的时候调用一次
// 图片验证码 点击的时候再获取一次验证码
const getCaptcha = async () => {
  // key判断验证码是否过期
  const key: string = new Date().getTime().toString()
  ruleForm.key = key
  const res = await captchaImage({ key })
  console.log(res)
  const blob = new Blob([res], { type: 'application/vnd.ms-excel' });
  const imgUrl = URL.createObjectURL(blob);
  captchaUrl.value = imgUrl;
  console.log(imgUrl)
}
// 生命周期 刚进页面的时候调用一次
onBeforeMount(() => {
  const userPwd: string | null = localStorage.getItem('user-pwd');
  if (userPwd) {
    const { username, password }: { username: string; password: string } = JSON.parse(userPwd)
    ruleForm.username = Decrypt(username)
    ruleForm.password = Decrypt(password)
  }
  getCaptcha()
})

// 登录功能
const login = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate(async (valid) => {
    if (valid) {
      const res = await LoginJson({
        username: Encrypt(ruleForm.username),
        password: Encrypt(ruleForm.password),
        key: ruleForm.key,
        captcha: ruleForm.captcha
      })
      //引入封装登录的hooks
      userLogin(res)
      // 记住密码
      setMemoPassWord()
    } else {
      return ElMessage.warning('请填写正确内容')
    }
    return;
  })
}
// 记住我
import useMemoPassWord from '@hooks/useMemoPassWord'; 
const { onMemoPassWord, memoVal } = useMemoPassWord()
const memoPassword: Ref<boolean> = ref(memoVal)
const setMemoPassWord = () => {
  if (memoPassword.value) {
    const userPwd: { username: string; password: string } = {
      username: Encrypt(ruleForm.username),
      password: Encrypt(ruleForm.password)
    }
    localStorage.setItem('user-pwd', JSON.stringify(userPwd))
  }
}
</script>

<style lang="scss" scoped>
.image_rule {
  display: flex;
  align-items: center;
  width: 100%;
}

.image {
  margin-left: 10px;
  height: 40px;
  width: 100px;
  cursor: pointer;
}

.rememberMe {
  font-size: 14px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}
</style>
